<template>
  <div class="setting-page p-d">
    <el-row class="p-d b-f search-content border-radius-8">
      <div class="form-box">
        <SearchComp :searchData="searchData"
          :searchForm="searchForm"
          :search-form-select-tree="searchFormSelectTree"
          :searchAction="searchHandle">
          <template v-slot:departmentName="{ item }">
            <el-select :ref="`selectBox${item.prop}`"
              v-model="searchData.departmentName"
              filterable
              :placeholder="item.placeholder"
              :clearable="item.clearable ? item.clearable : false"
              @clear="clearSelect">
              <el-option class="select-tree"
                :value="dataOrgTree">
                <div class="select-tree-box">
                  <el-scrollbar style="height: 100%">
                    <el-tree ref="tree"
                      class="orgTree elc-tree"
                      :data="dataOrgTree"
                      default-expand-all
                      node-key="id"
                      :expand-on-click-node="false"
                      highlight-current
                      :props="defaultProps"
                      @node-click="(data) => changeTree(data, item.prop)" />
                  </el-scrollbar>
                </div>
              </el-option>
            </el-select>
          </template>
        </SearchComp>
      </div>
    </el-row>
    <el-container class="bg-white-noP m-t border-radius-8">
      <el-aside width="330px"
        class="b-f m-r">
        <div class="org-left b-f">
          <el-tree ref="treeBox"
            v-loading="treeLoading"
            class="filter-tree org-tree"
            :data="dataOrgTree"
            :props="defaultProps"
            default-expand-all
            :highlight-current="true"
            :expand-on-click-node="false"
            node-key="id">
            <span slot-scope="{ node, data }"
              class="custom-tree-node">
              <span class="flex-span">
                <!-- <svg-icon class-name="international-icon" icon-class="file" /> -->
                <span class="org-name"
                  @click="() => clickNode(node, data)">{{
                  `${data.deptName ? data.deptName : "--"} (${data.nums ? data.nums : 0
                  })`
                }}</span>
              </span>
              <span v-if="data.id !== 0"
                class="btn-right">
                <el-dropdown trigger="click">
                  <span class="el-dropdown-link">
                    <i class="el-icon-more"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown"
                    class="org-dropdown">
                    <el-dropdown-item @click.native="() => handleDialog(node, data, '添加同级部门')">添加同级部门</el-dropdown-item>
                    <el-dropdown-item @click.native="() => handleDialog(node, data, '添加子部门')">添加子部门</el-dropdown-item>
                    <el-dropdown-item @click.native="() => handleDialog(node, data, '查看')">查看</el-dropdown-item>
                    <el-dropdown-item @click.native="() => handleDialog(node, data, '修改')">修改</el-dropdown-item>
                    <el-dropdown-item @click.native="() => delOrg(node, data)">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </span>
            </span>
          </el-tree>
        </div>
      </el-aside>
      <el-main class="b-f">
        <el-row class="p-r-l border-bottom-3 ">
          <p class="text-bf">
            <span v-if="currentObj"
              class="text-3-16-noBold">{{ currentObj.deptName }}成员</span>
            <span v-else
              class="text-3-16-noBold">单位成员</span>
          </p>
        </el-row>
        <el-row class="p-d">
          <el-row class="p-b">
            <el-button type="primary"
              @click="addUser()">添加成员</el-button>
            <el-button type="primary"
              @click="batchJoinUser()">批量加入部门</el-button>
            <el-button type="danger"
              @click="quitUsers()">批量移出成员</el-button>
          </el-row>
          <TableCompEle ref="multipleTable"
            v-loading="tableLoading"
            :tableData="tableData"
            :isSelect="true"
            :isIndex="true"
            :isShowPage="true"
            :tableConfig="tableConfig"
            @getPagination="getPagination"
            @handleSelectionChange="handleSelectionChange" />
        </el-row>
      </el-main>
    </el-container>
    <el-dialog :title="treeDialogTitle"
      :visible.sync="treeDialogVisible"
      width="600px"
      @close="cancel('treeDialogRuleForm')">
      <el-form ref="treeDialogRuleForm"
        :model="treeDialogRuleForm"
        :rules="treeDialogRules"
        label-width="150px"
        class="demo-ruleForm">
        <el-form-item label="单位名称"
          prop="deptName">
          <el-input v-model="treeDialogRuleForm.deptName"
            maxlength="64"
            :disabled="treeDialogTitle === '查看'" />
        </el-form-item>
        <el-form-item label="单位类别"
          prop="deptType">
          <el-input v-model="treeDialogRuleForm.deptType"
            maxlength="64"
            :disabled="treeDialogTitle === '查看'" />
        </el-form-item>
        <el-form-item label="通讯地址"
          prop="mailAddress">
          <el-input v-model="treeDialogRuleForm.mailAddress"
            maxlength="64"
            :disabled="treeDialogTitle === '查看'" />
        </el-form-item>
        <el-form-item label="单位负责人"
          prop="deptHead">
          <el-input v-model="treeDialogRuleForm.deptHead"
            maxlength="64"
            :disabled="treeDialogTitle === '查看'" />
        </el-form-item>
        <el-form-item label="联系电话"
          prop="deptPhone">
          <el-input v-model="treeDialogRuleForm.deptPhone"
            maxlength="64"
            :disabled="treeDialogTitle === '查看'" />
        </el-form-item>
        <el-form-item v-if="treeDialogTitle !== '查看'">
          <el-button type="primary"
            @click="submitForm('treeDialogRuleForm')">
            <span>确认</span>
          </el-button>
          <el-button @click="cancel('treeDialogRuleForm')">取消</el-button>
        </el-form-item>
        <el-form-item v-else-if="treeDialogTitle === '查看'">
          <el-button @click="cancel('treeDialogRuleForm')">关闭</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <OrgUsrDialog ref="orgUsrDialog" />
    <JoinOrgDialog ref="joinOrgDialog" />
  </div>
</template>

<script>
import OrgUsrDialog from './orgUsrDialog.vue'
import JoinOrgDialog from './joinOrgDialog.vue'
// import { departmentTree } from '@/api/projectManage'
import {
  // memberList,
  departmentCreate,
  departmentUpdate,
  departmentDetail,
  removeDepartment,
  quitDepartment
} from '@/api/department'
import { getUserInfo } from '@/utils/auth'
export default {
  components: { OrgUsrDialog, JoinOrgDialog },
  data() {
    return {
      power: {
        deptAdd: false, // 新建部门
        deptUpdate: false, // 修改部门
        deptDel: false, // 删除部门
        departmentName: ''
      },
      tableLoading: false,
      treeLoading: false,
      dataOrgTree: [],
      defaultProps: {
        children: 'childrenDept',
        label: 'deptName'
      },
      queryParams: {
        total: 0,
        pageNum: 1,
        pageSize: 10
      },
      searchFormSelectTree: [
        {
          type: 'Select',
          label: '部门名称',
          clearable: true,
          prop: 'departmentName',
          placeholder: '请选择部门'
        }
      ],
      searchForm: {
        changeMethod: () => {
          this.queryParams.pageNum = 1
          this.paginationSize()
        },
        formData: [
          {
            type: 'Input',
            label: '用户名称:',
            prop: 'userName',
            clearable: true,
            placeholder: '请输入用户名称',
            change: () => {
              this.paginationSize()
            }
          }
        ]
      },
      searchHandle: [
        {
          label: '重置',
          handle: () => this.reset()
        }
      ],
      searchData: {
        departmentName: null,
        departmentId: null,
        usersName: null
      },
      currentObj: null,
      tableData: [],
      tableConfig: [
        {
          prop: 'userName',
          label: '用户名称'
        },
        {
          prop: 'userRealName',
          label: '姓名'
        },
        {
          prop: 'roleName',
          label: '角色'
        },
        {
          prop: 'createTime',
          label: '创建时间'
        },
        {
          prop: 'createBy',
          label: '创建人'
        }
      ],
      treeDialogVisible: false,
      treeDialogTitle: '',
      treeDialogRuleForm: {
        deptName: '',
        deptType: '',
        mailAddress: '',
        deptHead: '',
        deptPhone: ''
      },
      treeDialogRules: {
        deptName: [
          { required: true, message: '请输入单位名称', trigger: 'blur' }
        ],
        deptType: [
          { required: true, message: '请输入单位类别', trigger: 'blur' }
        ],
        mailAddress: [
          { required: true, message: '请输入通讯地址', trigger: 'blur' }
        ]
      },
      nodeData: {},
      multipleSelection: [],
      userInfo: {}
    }
  },
  created() {
    this.userInfo = getUserInfo()
    this.setPower()
    this.initTree()
  },
  methods: {
    getPagination() {
      this.setPower()
    },
    setPower() {
      this.power.departmentName = this.userInfo.departmentName
    },
    initUser() {
      let res = {
        code: 200,
        total: 2,
        rows: [
          {
            userId: 1287,
            userName: 'admin',
            userRealName: '王滢熙',
            userEmail: null,
            deptName: null,
            createBy: 'admin',
            createTime: '2024-01-02 21:39:11',
            departmentName: '顶级部门',
            departmentId: null,
            selectFlag: true,
            userHeadPath: null,
            userPhone: null,
            enableFlag: null,
            roleName: '军医科-设施仪器管理员'
          },
          {
            userId: 1290,
            userName: 'xingsheng ',
            userRealName: '周兴盛',
            userEmail: null,
            deptName: null,
            createBy: '',
            createTime: '2024-01-16 15:10:09',
            departmentName: '顶级部门',
            departmentId: null,
            selectFlag: true,
            userHeadPath: null,
            userPhone: null,
            enableFlag: null,
            roleName: '主管机关'
          },
          {
            userId: 1280,
            userName: 'liujie',
            userRealName: '刘洁',
            userEmail: null,
            deptName: null,
            createBy: 'jiejie',
            createTime: '2024-01-16 15:10:09',
            departmentName: '顶级部门',
            departmentId: null,
            selectFlag: true,
            userHeadPath: null,
            userPhone: null,
            enableFlag: null,
            roleName: '大单位职能部门机关'
          },
          {
            userId: 1270,
            userName: 'tingyu',
            userRealName: '周婷玉',
            userEmail: null,
            deptName: null,
            createBy: 'jiejie',
            createTime: '2024-01-16 15:10:09',
            departmentName: '顶级部门',
            departmentId: null,
            selectFlag: true,
            userHeadPath: null,
            userPhone: null,
            enableFlag: null,
            roleName: '管理单位管理员'
          },
          {
            userId: 1270,
            userName: 'lili',
            userRealName: '周丽丽',
            userEmail: null,
            deptName: null,
            createBy: 'jiejie',
            createTime: '2024-01-16 15:10:09',
            departmentName: '顶级部门',
            departmentId: null,
            selectFlag: true,
            userHeadPath: null,
            userPhone: null,
            enableFlag: null,
            roleName: '设施仪器管理员'
          },
          {
            userId: 1270,
            userName: 'tongtong',
            userRealName: '李彤彤',
            userEmail: null,
            deptName: null,
            createBy: 'jiejie',
            createTime: '2024-01-16 15:10:09',
            departmentName: '顶级部门',
            departmentId: null,
            selectFlag: true,
            userHeadPath: null,
            userPhone: null,
            enableFlag: null,
            roleName: '用户单位管理员'
          },
          {
            userId: 1270,
            userName: 'zhudan',
            userRealName: '朱丹',
            userEmail: null,
            deptName: null,
            createBy: 'jiejie',
            createTime: '2024-01-16 15:10:09',
            departmentName: '顶级部门',
            departmentId: null,
            selectFlag: true,
            userHeadPath: null,
            userPhone: null,
            enableFlag: null,
            roleName: '平台中心管理员'
          }
        ]
      }
      // this.tableLoading = true
      // const params = {
      //   currentPage: this.queryParams.pageNum,
      //   pageSize: this.queryParams.pageSize,
      //   queryString: {
      //     userName: this.searchData.userName ? this.searchData.userName : '',
      //     departmentId: this.currentObj ? this.currentObj.id : ''
      //   }
      // }
      // memberList(params).then((res) => {
      this.tableData = res.rows
      this.total = res.total
      this.$refs.multipleTable.clearSelection()
      // })
      //   .finally(() => {
      //     this.tableLoading = false
      //   })
    },
    initTree() {
      let res = {
        code: 200,
        message: '执行成功',
        data: [
          {
            id: 77,
            deptName: '顶级部门',
            nums: 7,
            deptParentId: 0,
            childrenDept: [
              {
                id: 1,
                deptName: '陆军机关',
                nums: 0,
                deptParentId: 77,
                childrenDept: [
                  {
                    id: 29,
                    deptName: '陆军研究院',
                    nums: 0,
                    deptParentId: 1,
                    childrenDept: [
                      {
                        id: 31,
                        deptName: '陆军研究院第一研究所',
                        nums: 0,
                        deptParentId: 29,
                        childrenDept: []
                      },
                      {
                        id: 51,
                        deptName: '陆军研究院第二研究所',
                        nums: 0,
                        deptParentId: 29,
                        childrenDept: []
                      }
                    ]
                  }
                ]
              },
              {
                id: 32,
                deptName: '海军机关',
                nums: 0,
                deptParentId: 77,
                childrenDept: [
                  {
                    id: 33,
                    deptName: '海军工程大学',
                    nums: 0,
                    deptParentId: 32,
                    childrenDept: []
                  },
                  {
                    id: 34,
                    deptName: '海军装备研究院',
                    nums: 0,
                    deptParentId: 32,
                    childrenDept: []
                  }
                ]
              },
              {
                id: 37,
                deptName: '空军机关',
                nums: 0,
                deptParentId: 77,
                childrenDept: [
                  {
                    id: 38,
                    deptName: '空军装备研究院',
                    nums: 0,
                    deptParentId: 37,
                    childrenDept: [
                      {
                        id: 39,
                        deptName: '空军装备第一研究所',
                        nums: 0,
                        deptParentId: 38,
                        childrenDept: []
                      }
                    ]
                  },
                  {
                    id: 39,
                    deptName: '空军工程大学',
                    nums: 0,
                    deptParentId: 37,
                    childrenDept: []
                  }
                ]
              },
              {
                id: 50,
                deptName: '火箭军机关',
                nums: 0,
                deptParentId: 77,
                childrenDept: [
                  {
                    id: 80,
                    deptName: '火箭军工程大学',
                    nums: 0,
                    deptParentId: 77,
                    childrenDept: []
                  }
                ]
              }
            ]
          },
          {
            id: 0,
            deptName: '未分配部门',
            nums: 2,
            deptParentId: null,
            childrenDept: []
          }
        ]
      }
      // departmentTree().then(res => {
      this.dataOrgTree = res.data
      console.log(this.dataOrgTree)
      if (!this.currentObj) {
        this.currentObj = res.data[0]
      }
      this.initUser()
      this.$nextTick(() => {
        this.$refs.treeBox.setCurrentKey(this.currentObj.id)
      })
      // }).catch(err => {
      //   console.log(err)
      // })
    },
    changeTree(data, prop) {
      this.searchData.departmentName = data.deptName
      this.searchData.departmentId = data.id
      this.$refs[`selectBox${prop}`].blur()
      this.currentObj = data
      this.$nextTick(() => {
        this.$refs.treeBox.setCurrentKey(this.currentObj.id)
      })
      this.paginationSize()
    },
    clearSelect() {
      this.searchData.departmentName = ''
      this.searchData.departmentId = ''
      this.currentObj = null
      this.$nextTick(() => {
        this.$refs.treeBox.setCurrentKey(null)
      })
      this.paginationSize()
    },
    paginationSize() {
      this.queryParams.pageNum = 1
      this.initUser()
    },
    reset() {
      this.searchData = {
        departmentName: null,
        departmentId: null,
        usersName: null,
        enableFlag: null,
        roleId: null
      }
      this.paginationSize()
    },
    clickNode(node, data) {
      this.currentObj = data
      this.initUser()
    },
    handleDialog(node, data, title) {
      this.treeDialogTitle = title
      this.treeDialogVisible = true
      this.nodeData = data
      if (this.treeDialogTitle === '查看' || this.treeDialogTitle === '修改') {
        departmentDetail(this.nodeData.id).then(res => {
          this.treeDialogRuleForm = {
            deptName: res.data.deptName.trim(),
            deptType: res.data.deptType.trim(),
            mailAddress: res.data.mailAddress.trim(),
            deptHead: res.data.deptHead.trim(),
            deptPhone: res.data.deptPhone.trim()
          }
        })
      }
    },
    delOrg(node, data) {
      this.nodeData = data
      this.$confirm(`本操作将删除部门，是否继续？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          removeDepartment({ id: this.nodeData.id })
            .then(() => {
              this.currentObj = null
              this.initTree()
            })
            .catch(() => {
              this.initTree()
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    submitForm(formName) {
      if (this.treeDialogRuleForm.deptName === '顶级部门') {
        this.$message({
          message: '单位名称无效',
          type: 'error'
        })
        return false
      }

      this.$refs[formName].validate(valid => {
        if (valid) {
          const params = {
            deptName: this.treeDialogRuleForm.deptName.trim(),
            deptType: this.treeDialogRuleForm.deptType.trim(),
            mailAddress: this.treeDialogRuleForm.mailAddress.trim(),
            deptHead: this.treeDialogRuleForm.deptHead.trim(),
            deptPhone: this.treeDialogRuleForm.deptPhone.trim()
          }

          if (this.treeDialogTitle === '添加同级部门') {
            params.deptParentId = this.nodeData.deptParentId
          } else if (this.treeDialogTitle === '添加子部门') {
            params.deptParentId = this.nodeData.id
          } else if (this.treeDialogTitle === '修改') {
            params.id = this.nodeData.id
            params.deptParentId = this.nodeData.deptParentId
          }

          if (this.treeDialogTitle === '修改') {
            departmentUpdate(params)
              .then(res => {
                if (res.code === 200) {
                  this.$message({
                    message: '修改成功',
                    type: 'success'
                  })
                } else {
                  this.$message({
                    message: res.message,
                    type: 'error'
                  })
                }
                this.currentObj = null
                this.initTree()
              })
              .catch(err => {
                this.$message({
                  message: err.message,
                  type: 'error'
                })
                this.currentObj = null
                this.initTree()
              })
              .finally(() => {
                this.cancel('treeDialogRuleForm')
              })
          } else {
            departmentCreate(params)
              .then(res => {
                if (res.code === 200) {
                  this.$message({
                    message: '新增成功',
                    type: 'success'
                  })
                } else {
                  this.$message({
                    message: res.message,
                    type: 'error'
                  })
                }
                this.currentObj = null
                this.initTree()
              })
              .catch(err => {
                this.$message({
                  message: err.message,
                  type: 'error'
                })
                this.currentObj = null
                this.initTree()
              })
              .finally(() => {
                this.cancel('treeDialogRuleForm')
              })
          }
        } else {
          return false
        }
        this.treeDialogVisible = false
      })
    },
    cancel(formName) {
      this.$refs[formName].resetFields()
      this.treeDialogVisible = false
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    addUser() {
      if (this.currentObj === null || this.currentObj === undefined) {
        this.currentObj = this.dataOrgTree[0]
      }
      this.$refs.orgUsrDialog.show(this.currentObj)
    },
    batchJoinUser() {
      if (this.multipleSelection && this.multipleSelection.length === 0) {
        this.$message.warning('请选择需要加入的用户！')
        return false
      }
      this.$refs.joinOrgDialog.show(this.multipleSelection)
    },
    quitUsers() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请先选择用户！')
        return false
      }
      this.$confirm(`本操作将移出用户，是否继续？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const userIds = []
          this.multipleSelection.forEach(item => {
            userIds.push(item.userId)
          })
          const params = {
            departmentId: this.currentObj.id,
            userIds: userIds
          }
          quitDepartment(params).then(() => {
            this.paginationSize()
            this.initTree()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    }
  }
}
</script>

<style lang="less" scoped>
.orgs {
  .el-aside {
    height: 750px;
    border-right: 1px solid #f2f2f2;
    scrollbar-width: none;
    /* firefox */
    -ms-overflow-style: none;
    /* IE 10+ */
  }

  .el-aside::-webkit-scrollbar {
    display: none;
    /* Chrome Safari */
  }

  .org-tree {
    .el-tree-node__content {
      display: flex;
    }

    .custom-tree-node {
      display: flex;
      flex: 1;
      justify-content: space-between;
      padding-right: 20px;
    }

    .custom-tree-node {
      font-size: 14px;
      color: #333;
    }
  }

  .left-head {
    display: flex;
    align-items: center;
    justify-content: space-between;

    i {
      display: inline-block;
      width: 24px;
      height: 24px;
      line-height: 24px;
      text-align: center;
      background: #f8f8f8;
      color: #333;
      border-radius: 2px;

      &:hover {
        cursor: pointer;
        background-color: #4986ff1f;
      }
    }
  }
}

.p-t-20 {
  padding-top: 20px;
}

.org-left {
  .org-tree {
    .el-tree-node__content {
      display: flex;
    }

    .custom-tree-node {
      display: flex;
      flex: 1;
      justify-content: space-between;
      padding-right: 20px;
      font-size: 14px;
      color: #333;
      width: 100%;
      height: 17px;
    }

    .custom-tree-node span:nth-child(1) {
      padding-left: 5px;
    }
  }

  .left-head {
    display: flex;
    align-items: center;
    justify-content: space-between;

    i {
      display: inline-block;
      width: 24px;
      height: 24px;
      line-height: 24px;
      text-align: center;
      background: #f8f8f8;
      color: #333;
      border-radius: 2px;

      &:hover {
        cursor: pointer;
        background-color: #4986ff1f;
      }
    }
  }
}

::v-deep.org-tree {
  padding-left: 20px;
  padding-top: 20px;
  padding-bottom: 20px;

  .org-left .el-input__inner {
    border-color: transparent;
  }

  .el-tree-node__expand-icon {
    color: #999;
  }

  .el-tree-node__content {
    height: 40px;
  }

  .el-tree-node__expand-icon.is-leaf {
    position: relative;
  }

  .el-tree-node__expand-icon.is-leaf::before {
    display: inline-block;
    content: '';
    width: 4px;
    height: 4px;
    background: #999999;
    border-radius: 50%;
    position: absolute;
    top: 4px;
    left: 10px;
  }

  .el-tree-node:focus > .el-tree-node__content,
  .el-tree-node__content:hover {
    background: #e1f5ef;
  }
}

.flex-span {
  width: 80%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.flex-span .org-name {
  display: flex;
  flex: 1;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.btn-right {
  display: inline-block;
  position: absolute;
  right: 14px;
  z-index: 10 !important;
}

::v-deep.btn-right .el-dropdown-link {
  padding-left: 0 !important;
}

.org-dropdown .el-dropdown-menu__item:hover {
  background: #e1f5ef;
  color: #333333;
  font-family: PingFangSC-Regular, PingFang SC;
}

.bg-white-noP {
  height: 79vh;
}
</style>
